package cn.ltgodm.template.user.service.impl;

import cn.ltgodm.template.common.constant.CacheConstants;
import cn.ltgodm.template.common.constant.Constants;
import cn.ltgodm.template.common.constant.UserConstants;
import cn.ltgodm.template.common.domain.entity.User;
import cn.ltgodm.template.common.exception.ServiceException;
import cn.ltgodm.template.common.exception.user.CaptchaException;
import cn.ltgodm.template.common.exception.user.UserNotExistsException;
import cn.ltgodm.template.common.exception.user.UserPasswordNotMatchException;
import cn.ltgodm.template.common.utils.MessageUtils;
import cn.ltgodm.template.common.utils.RedisCache;
import cn.ltgodm.template.common.utils.SecurityUtils;
import cn.ltgodm.template.common.utils.StringUtils;
import cn.ltgodm.template.user.domain.param.RegisterParam;
import cn.ltgodm.template.user.domain.param.UserParam;
import cn.ltgodm.template.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.sql.rowset.serial.SerialException;

/**
 * @author ltgodm
 * @date 2024-03-22 09:33:58
 * 注册业务
 */
@Component
public class RegisterService {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserService userService;

    @Value("${user.captcha.enable}")
    private boolean captchaEnable;

    /**
     * 用户注册
     * @param registerParam 用户参数
     * @return 返回注册信息
     */
    public int register(RegisterParam registerParam) {
        String msg = "", username = registerParam.getUsername(), password = registerParam.getPassword();
        User userDB = new User();
        userDB.setUserName(username);
        if (captchaEnable){
            validateCaptcha(username,registerParam.getCode(),registerParam.getUuid());
        }
        registerPreCheck(username,password);

        if (!userService.checkUserNameUnique(userDB)) {
            throw new ServiceException(MessageUtils.message("保存用户 {} 失败，注册账号已存在",username));
        }

        userDB.setNickName(username);
        userDB.setPassword(SecurityUtils.encryptPassword(password));
        int row =  userService.registerUser(userDB);
        userService.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success"));
        return row;
    }



    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     验证码唯一标识
     */
    private void validateCaptcha(String username, String code, String uuid) {
        //验证码是否开启
        if (captchaEnable) {
            String verify = CacheConstants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisCache.getCacheObject(verify);
            redisCache.deleteObject(verify);
            if (StringUtils.isEmpty(captcha)) {
                //验证码已过期
                throw new CaptchaException();
            } else if (!code.equalsIgnoreCase(captcha)) {
                //验证码不正确
                throw new CaptchaException();
            }
        }
    }


    /**
     * 注册前置校验
     *
     * @param username 用户名
     * @param password 密码
     */
    private void registerPreCheck(String username, String password) {
        //用户名密码为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new UserNotExistsException();
        }
        //账号不在指定范围
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }
        //密码不在指定范围
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }
        //todo ip黑名单校验

    }
}
